package com.py.framework.core.helper;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.py.framework.core.common.URLConstants;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.filter.SecurityCheckFilter;
import com.py.framework.core.http.HttpAsyncAgent;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.log.OutInterfaceLogger;
import com.py.framework.core.log.SystemLogger;
import com.py.framework.core.rest.support.RestServiceResult;

/**
 * 系统日志辅助类
 * @author Leegern
 * @date   2018年5月2日
 */
public class SysLogHelper {
	
	/** 默认字符集  **/
	public static final String CHARSET_UTF_8 = "utf-8";
	
	/** 请求日志服务地址 **/
	public static final String REQUEST_PATH  = URLConstants.POST_LOG_URL;
	
	
	/**
	 * 异步发送日志
	 * @param jdToken 用户口令
	 * @param baseUrl 请求的url
	 * @param jsonStr 参数, 格式是json
	 */
	public static void postAsyncSysLog(String jdToken, String baseUrl, String jsonStr) {
//		if (StringUtils.isBlank(jdToken)) {
//			SystemLogger.info("we don't have jdToken, check config !");  
//            throw new ServiceException("we don't have jdToken, check config !");  
//		}
		if (StringUtils.isBlank(baseUrl)) {  
            SystemLogger.info("we don't have base url, check config !");  
            throw new ServiceException("we don't have base url, check config !");  
        }  
        CloseableHttpAsyncClient hc = HttpAsyncAgent.getInstance().getAsyncHttpClient();
        hc.start();  
        HttpPost httpPost = new HttpPost(baseUrl + REQUEST_PATH);  

        httpPost.setHeader("Connection","close");
        if (StringUtils.isNotBlank(jdToken)) {
        	httpPost.setHeader(SecurityCheckFilter.Token, jdToken);
        }
        
        if (StringUtils.isNotBlank(jsonStr)) {
        	StringEntity entity = new StringEntity(jsonStr, CHARSET_UTF_8);  
            entity.setContentEncoding(CHARSET_UTF_8);  
            entity.setContentType("application/json");  
            httpPost.setEntity(entity);  
        }
        hc.execute(httpPost, new FutureCallback<HttpResponse>() {
        	/*
        	 * (non-Javadoc)
        	 * @see org.apache.http.concurrent.FutureCallback#completed(java.lang.Object)
        	 */
			@Override
			public void completed(HttpResponse result) {
				try {
					String data = EntityUtils.toString(result.getEntity());
					if (StringUtils.isNotBlank(data)) {
						RestServiceResult<Object> rs = JSON.parseObject(data, new TypeReference<RestServiceResult<Object>>(){});
						if (null != rs) {
							if (rs.getCode() == RestServiceResult.CODE_SUCCESS) {
								OutInterfaceLogger.info("postAsyncSysLog success[jdToken=" + jdToken + "]", baseUrl, null, jsonStr, null, data);
							} else {
								OutInterfaceLogger.info("postAsyncSysLog failed[jdToken=" + jdToken + "]", baseUrl, null, jsonStr, null, data);
							}
						}
					}
				} catch (IOException e) {
					ExceptionLogger.error(e);
				}
			}
			/*
			 * (non-Javadoc)
			 * @see org.apache.http.concurrent.FutureCallback#failed(java.lang.Exception)
			 */
			@Override
			public void failed(Exception ex) {
				ExceptionLogger.error("" ,"postAsyncSysLog error[" + baseUrl + "], and token[" + jdToken + "], params[" + jsonStr + "]", ex);
			}
			/*
			 * (non-Javadoc)
			 * @see org.apache.http.concurrent.FutureCallback#cancelled()
			 */
			@Override
			public void cancelled() {
				
			}
        });  
	}
}